
import mimetypes
from app.utils.filesystem.StorageDriver import StorageDriver
from app import myApp

class FileUtils:
    defalutDisk=""
    config={}
    diskConfig={}
    driver:StorageDriver=None
    def __init__(self) -> None:
        self.defalutDisk=myApp.config['filesystem']['default']
        self.config=myApp.config['filesystem']
        self.diskConfig=self.getDiskConfig(self.defalutDisk)
        self.setDriver()

    def getDiskConfig(self,disk):
        if disk in self.config['disks']:
            return self.config['disks'][disk]
        else:
            return None
        
    def setDiskConfig(self,disk):
        if disk!=None:
            self.defalutDisk=disk
        self.diskConfig=self.getDiskConfig(self.defalutDisk)

    def setDriver(self):
        config=self.getDiskConfig(self.defalutDisk)
        if config:
            driver=config['driver']
            if driver=='local':
                from app.utils.filesystem.LocalFile import LocalFile
                self.driver=LocalFile(self.defalutDisk,config)
            elif driver=='s3':
                from app.utils.filesystem.S3File import S3File
                self.driver=S3File(self.defalutDisk,config)
            elif driver=='aliyun':
                from app.utils.filesystem.AliyunFile import AliyunFile
                self.driver=AliyunFile(self.defalutDisk,config)
            else:
                raise Exception('Unknown driver')
        else:
            raise Exception('Disk not found in config')
    
    def upload(self,file,filename=None):
        return self.driver.upload(file,filename)
    
    @staticmethod
    def getExtention(filename):
        return filename.split('.')[-1]
    
    @staticmethod
    def getMimeType(filename):
        extention=FileUtils.getExtention(filename)
        return mimetypes.types_map[extention]